package org.hackystat.timeline.service;

import org.hackystat.timeline.resource.timelinedata.TimelineDataResource;
import org.hackystat.timeline.resource.timelineproperties.TimelinePropertiesResource;
import org.restlet.Application;
import org.restlet.Component;
import org.restlet.Restlet;
import org.restlet.Router;
import org.restlet.data.Protocol;

/**
 * Sets up the HTTP Server process and dispatching to the associated resources.
 * 
 * @author Alexey R. Olkov
 * 
 */
public class Service extends Application {
  /**
   * Host name.
   */
  private String hostName;

  /**
   * Component associated with the service.
   */
  private Component component;

  /**
   * Starts up the Timeline Service on port 9875.
   * 
   * @param args Ignored.
   * @throws Exception if problems occur.
   */
  public static void main(final String[] args) throws Exception {
    Service.newInstance("http://localhost", 9875);
  }

  /**
   * Creates a new instance of the component that has a server associated with it.
   * 
   * @param host Host name
   * @param port Port number.
   * @throws Exception If Problems occured
   * @return Service a service with the component running
   */
  public static Service newInstance(String host, int port) throws Exception {
    Service service = new Service();
    System.out.println("Service is now running...");
    service.component = new Component();
    service.hostName = host + ":" + port;
    // Add an HTTP server connector that would listen the
    service.component.getServers().add(Protocol.HTTP, port);
    // Attach Service to the local host
    service.component.getDefaultHost().attach("/timelineservice", service);
    service.component.start();
    return service;
  }

  /**
   * Dispatches to the TimelineData resource.
   * 
   * @return The router Restlet.
   */
  @Override
  public Restlet createRoot() {
    System.out.println("SERVICE TALKS");
    TimelineDataResource.setHostName(this.hostName);
    Router router = new Router(getContext());
    // router.attach("", new FileDispatcher(getContext()));
    // router.attach("/translated/{userkey}", new FileDispatcher(getContext()));
    router.attach(
        "/translated/{userkey}/{projectname}/{sensordatatype}/{start_timestamp}/{end_timestamp}",
        TimelineDataResource.class);

    router.attach(
        "/{userkey}/properties/{projectname}",
        TimelinePropertiesResource.class);
    return router;
  }

  /**
   * Returns host name.
   * 
   * @return host name
   */
  public String getHostName() {
    return this.hostName;
  }
}
